package com.blacksea.resourceserver.web.security.util;

import com.blacksea.resourceserver.web.security.response.OAuth2CommonResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

import javax.servlet.ServletResponse;

/**
 * 响应类, 仅在web模块使用
 *
 * @author blacksea3(jxt) 2021/2/6 23:08
 */
@Component
public class ResponseUtilObject {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 输出JSON
     *
     * @param response .
     * @param OAuth2CommonResponse .
     * @throws Exception .
     */
    public void outJson(ServletResponse response, OAuth2CommonResponse OAuth2CommonResponse)
        throws Exception {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(objectMapper.writeValueAsString(OAuth2CommonResponse));
        } catch (Exception e) {
            throw new Exception("输出JSON出错");
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    // /**
    //  * 响应内容
    //  * @param httpServletResponse
    //  * @param msg
    //  * @param status
    //  */
    // public static void getResponse(HttpServletResponse httpServletResponse, String msg, Integer status){
    //    PrintWriter writer = null;
    //    httpServletResponse.setCharacterEncoding("UTF-8");
    //    httpServletResponse.setContentType("application/json; charset=utf-8");
    //    try {
    //        writer = httpServletResponse.getWriter();
    //        writer.print(JSONObject.toJSONString(new ApiResult(status,msg,null)));
    //    } catch (IOException e) {
    //        log.error("响应报错", e.getMessage());
    //    } finally {
    //        if (writer != null){
    //            writer.close();
    //        }
    //    }
    // }

}
